package csl.blog.server.mq.consumer;

import cn.hutool.json.JSONObject;
import com.rabbitmq.client.Channel;
import csl.blog.server.mq.consumer.service.AsyncEventService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Slf4j
@Service("eventConsumer")
public class EventConsumer {

    @Autowired
    private AsyncEventService asyncEventService;

    @RabbitListener(queues = "async_event", containerFactory = "customContainerFactory")
    public void receiveEvent(final JSONObject message, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) throws IOException {
        asyncEventService.receiveEvent(message,deliveryTag,channel);

    }

    @RabbitListener(queues = "async_event_dead", containerFactory = "customContainerFactory")
    public void receiveDeadEvent(final JSONObject message, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) throws IOException {
        log.error("Handle failed message." + message);
        channel.basicAck(deliveryTag, false);
    }
}
